package com.walking.db;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author walking
 * 公众号：编程大道
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    /**
     * 支持以包名的粒度选择数据源
     */
    private static final Map<String,DataSourceName> packageDataSource = new HashMap<>();

    public DynamicDataSource(DataSource firstDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(firstDataSource);
        super.setTargetDataSources(targetDataSources);
    }

    /**
     * 获取与线程上下文绑定的数据源名称（存储在ThreadLocal中）
     * @return 返回数据源名称
     */
    @Override
    protected Object determineCurrentLookupKey() {
        DataSourceName dataSourceName = DataSourceHolder.getDataSourceName();
        log.info("===当前数据源：{}====",dataSourceName==null?"default":dataSourceName.toString());
        return dataSourceName;
    }
    public static DataSourceName getPackageDatasource(String pkName){
        return packageDataSource.get(pkName);
    }

    public void setPackageDatasource(Map<String,DataSourceName> packageDatasource){
        packageDataSource.putAll(packageDatasource);
    }
}